import { AudioClip, Combinator, ImgClip, OffscreenSprite } from '@webav/av-cliper';

// 转换 Base64 数据为 Uint8Array
function dataURLToUint8Array(dataURL: string) {
  // 去掉 `data:image/png;base64,` 头部
  const base64 = dataURL.split(',')[1];
  const binaryString = atob(base64);
  const len = binaryString.length;
  const bytes = new Uint8Array(len);
  for (let i = 0; i < len; i++) {
    bytes[i] = binaryString.charCodeAt(i);
  }
  return bytes;
}

// 创建 ReadableStream
function createReadableStream(uint8Array: Uint8Array) {
  return new ReadableStream({
    start(controller) {
      // 将 Uint8Array 推入流中
      controller.enqueue(uint8Array);
      controller.close(); // 标记流结束
    }
  });
}

// 获取音频时间长度
async function getAudioDuration(audioUrl: string) {
  const audio = new Audio();
  audio.src = audioUrl;
  let duration = 0;
  await new Promise((resolve, reject) => {
    audio.addEventListener('loadedmetadata', () => {
      duration = audio.duration;
      resolve(true);
      audio.remove();
    });
    audio.addEventListener('error', () => {
      reject(new Error('音频加载失败'));
    });
  });
  console.log(duration, 'audio.duration');
  return duration;
}

export async function start(imageUrl: string, audioUrl: string) {
  // 将 dataURL 转化为 Uint8Array
  const uint8Array = dataURLToUint8Array(imageUrl);
  // 创建流
  const readableStream = createReadableStream(uint8Array);
  const audioDuration = await getAudioDuration(audioUrl);
  console.log(audioUrl, 'audioUrl=====audioUrl');
  const gifSpr = new OffscreenSprite(new ImgClip({ type: 'image/png', stream: readableStream }));
  gifSpr.time = { duration: audioDuration * 1e6, offset: 0 };
  const audioSpr = new OffscreenSprite(new AudioClip((await fetch(audioUrl)).body!));
  audioSpr.time = { duration: audioDuration * 1e6, offset: 0 };
  const com = new Combinator({ width: 1280, height: 720 });
  await com.addSprite(gifSpr);
  await com.addSprite(audioSpr);
  return {
    combinator: com,
    cleanup: async () => {
      // 释放 Sprite 资源
      await gifSpr.destroy();
      await audioSpr.destroy();
      // 释放合成器资源
      await com.destroy();
    }
  };
}
